#include "server.h"

int get_path(const char* current_dir, const char* path, char *temp_path) {
    if (strcmp(path, ".") == 0)
    {
        /* code */
        snprintf(temp_path, PATH_MAX, "%s", current_dir);
        return 0;
    }
    if ((strcmp(path, "..") == 0))
    {
        /* code */
        if (strcmp(current_dir, "/") == 0)
        {
            /* code */
            snprintf(temp_path, PATH_MAX, "%s", current_dir);
            return 0;
        }

        int len = strlen(current_dir);
        int i = 0;
        for (i = len - 2; i >= 0; i--) {
            if (current_dir[i] == '/') {
                // 找到前面的'/'后,将其后面的字符设为'\0'
                break;
            }
        }
        //类似截断功能
		len = i + 2;
        //第二个参数len是写入字符的最大数目,最多写入len-1个字符
        snprintf(temp_path, len, "%s", current_dir);
        
        return 0;
    }

    strcpy(temp_path, current_dir);
    strcat(temp_path, path);
    strcat(temp_path, "/");
    return 0;
}
//server->client[client_index].root_dir
//server->client[client_index].current_dir
//path
int handle_cd(int net_fd, ClientInfo *client, const char* path) {
    client->socket = net_fd;

    Message response = {0};

    char temp_path[PATH_MAX] = {0};
    //拼接完整路径
    get_path(client->current_dir, path, temp_path);

    char full_path[PATH_MAX] = {0};
    strcpy(full_path, client->root_dir);
    strcat(full_path, temp_path);

    struct stat st = {0};
    // 使用 stat 函数检查用户目录是否存在
    // 如果 stat 返回 -1，表示目录不存在
    if (stat(full_path, &st) == -1) {
        response.type = MSG_TYPE_FAIL;
        response.length = snprintf(response.data, sizeof(response.data), "目录不存在: %s, 切换失败", temp_path);
    } else {
        // 更新客户端的当前目录
        strncpy(client->current_dir, temp_path, PATH_MAX);
        
        response.type = MSG_TYPE_SUCCESS;
        response.length = snprintf(response.data, sizeof(response.data), "%s", client->current_dir);
    }

    if (send_message(client->socket, &response) < 0) {
        perror("发送cd响应失败");
        return -1;
    }

    return 0;
}
